<template>
  <div class="spurs-dialog">
    <el-dialog
      v-model="dialogVisible"
      :append-to-body="true"
      :title="title"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      draggable
    >
      <SpursForm
        ref="spursFormRef"
        v-bind="formConfig"
        :modelValue="modelValue"
        :rules="rules"
      >
        <template #special>
          <!-- :http-request="customRequest" -->
          <div class="special">
            <el-upload
              accept="image/jpeg,image/png"
              :action="`${VITE_API_PREFIX}/file/fileUpload`"
              :file-list="fileList"
              list-type="picture-card"
              :before-upload="beforeUpload"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :on-error="handleError"
              :on-preview="handlePreview"
              :limit="5"
              multiple
            >
              <el-icon><Plus /></el-icon>
              <template #tip>
                <div class="el-upload__tip">
                  最多可上传5张图片，JPG/PNG格式，单张不超过5MB
                </div>
              </template>
            </el-upload>
            <el-dialog v-model="dialogVisibleImageUrl" title="图片预览">
              <img
                style="width: 100%; max-width: 500px"
                :src="dialogImageUrl"
                alt="Preview Image"
              />
            </el-dialog>
          </div>
        </template>
      </SpursForm>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="saveSubmit"> 确 定 </el-button>
          <slot name="footer"></slot>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, watch, reactive, onMounted } from "vue";
import SpursForm from "@/components/SpursForm/index.vue";
import { getFormConfig } from "@/components/addEditDialog/product/FormConfig";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import cloneDeep from "lodash/cloneDeep";
import productApi from "@/api/product";
import type { UploadUserFile } from "element-plus";
import { FormOption } from "@/components/SpursForm/formType";
import { isValidAmount, safeNumber } from "@/utils/precision";
const formConfig = ref<FormOption>({
  formItems: [],
  labelWidth: "120px",
});
const VITE_API_PREFIX = ref(import.meta.env.VITE_API_PREFIX);
const categoryList = ref<{ id: string; name: string }[]>([]);
const spursFormRef = ref<any>();
const rules = reactive<FormRules>({
  pName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  categoryId: [{ required: true, message: "请选择商品分类", trigger: "blur" }],
  pBrand: [{ required: true, message: "请输入商品品牌", trigger: "blur" }],
  pSpecifications: [
    { required: true, message: "请输入商品规格", trigger: "blur" },
  ],
  pNumber: [
    { required: true, message: "请输入商品数量", trigger: "blur" },
    {
      validator: (rule: any, value: any, callback: any) => {
        // 转换为安全数字
        const num = safeNumber(value, -1);

        // 检查是否为非负整数
        if (num < 0 || !Number.isInteger(num)) {
          callback(new Error("请输入有效的非负整数"));
          return;
        }

        callback();
      },
    },
  ],
  pPrice: [
    { required: true, message: "请输入商品单价", trigger: "blur" },
    {
      validator: (rule: any, value: any, callback: any) => {
        // 使用精度工具验证金额
        if (!isValidAmount(value, false)) {
          callback(new Error("请输入有效的正数金额，最多2位小数"));
          return;
        }

        // 检查小数位数
        const str = value.toString();
        if (str.includes(".")) {
          const decimalPlaces = str.split(".")[1].length;
          if (decimalPlaces > 2) {
            callback(new Error("价格最多保留2位小数"));
            return;
          }
        }

        callback();
      },
    },
  ],
  pType: [{ required: true, message: "请输入商品型号", trigger: "blur" }],
  deliveryDays: [
    {
      validator: (rule: any, value: any, callback: any) => {
        // 空值检查
        if (value === "" || value === null || value === undefined) {
          callback();
          return;
        }

        // 转换为安全数字并验证
        const num = safeNumber(value, -1);

        // 检查是否为非负整数
        if (num < 0 || !Number.isInteger(num)) {
          callback(new Error("请输入有效的非负整数天"));
          return;
        }

        callback();
      },
    },
  ],
});
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      addEditFun();
    } else {
      // spursFormRef.value.ruleFormRef.clearValidate()
    }
  });
};

let modelValue = ref<any>({});
const props = defineProps({
  visible: { type: Boolean, default: false },
  title: { type: String, default: "新增" },
  formData: { type: Object, default: {} },
});
const addEditFun = async () => {
  let res = null;
  // 将fileList中的url拼接成字符串，处理不同来源的URL
  const imageUrls = fileList.value
    .map((item: any) => {
      // 如果是新上传的文件，从response中获取URL
      if (
        item.response &&
        item.response.data &&
        item.response.data.data &&
        item.response.data.data.url
      ) {
        return item.response.data.data.url;
      }
      // 如果是已存在的文件（编辑模式），直接使用URL
      if (item.url) {
        return item.url;
      }
      // 如果都没有，返回空字符串
      return "";
    })
    .filter((url) => url.trim()); // 过滤掉空字符串

  modelValue.value.pImgUrl = imageUrls.join(",");

  if (props.title == "新增") {
    res = await productApi.addProduct(modelValue.value);
  } else {
    const id = (props.formData as any).id;
    res = await productApi.editProduct(id, modelValue.value);
  }
  emit("saveSubmit", res);
};
const emit = defineEmits(["update:visible", "saveSubmit"]);
let dialogVisible = ref(props.visible);
watch(
  () => props.visible,
  (newValue) => {
    dialogVisible.value = newValue;
    if (newValue) {
      modelValue.value = cloneDeep(props.formData);
      // 如果是编辑模式且有图片URL，显示在文件列表中
      const imageUrls = (props.formData as any)?.pImgUrl;
      if (imageUrls) {
        // 处理多个图片URL（用逗号分隔）
        const urls = imageUrls.split(",").filter((url: string) => url.trim());

        fileList.value = urls.map((url: string, index: number) => ({
          name: `product-image-${index + 1}`,
          url: url.trim(),
          status: "success",
        }));
      } else {
        fileList.value = [];
      }
    } else {
      modelValue.value = {};
      fileList.value = [];
    }
  }
);
watch(
  () => dialogVisible.value,
  (newValue) => {
    emit("update:visible", newValue);
  }
);
// 获取商品分类列表
const getCategoryList = async () => {
  const res = await productApi.getCategoryList();
  const mappedList = res.data.list.map((item: any) => ({
    value: item.id,
    label: item.name,
  }));
  categoryList.value = res.data.list;
  return mappedList;
};
onMounted(async () => {
  const mappedList = await getCategoryList();
  formConfig.value = getFormConfig(mappedList);
});
const fileList = ref<UploadUserFile[]>([]);
// 上传前回调
const beforeUpload = (file: any) => {
  const isJPGorPNG = file.type === "image/jpeg" || file.type === "image/png";
  const isLt5MB = file.size / 1024 / 1024 < 5;

  if (!isJPGorPNG) {
    ElMessage.error("只能上传JPG/PNG格式的图片!");
    return false;
  }
  if (!isLt5MB) {
    ElMessage.error("图片大小不能超过5MB!");
    return false;
  }
  return true;
};
// 移除文件的回调
const handleRemove = (file: any, uploadFileList: any) => {
  console.log("移除文件:", file, uploadFileList);
  // 更新文件列表
  fileList.value = uploadFileList;

  ElMessage.info("图片已移除");
};

// 预览图片
const handlePreview = (file: UploadUserFile) => {
  dialogImageUrl.value = file.url || "";
  dialogVisibleImageUrl.value = true;
};
// 成功回调
const handleSuccess = (response: any, file: any, uploadFileList: any) => {
  fileList.value = uploadFileList;
};
// 失败回调
const handleError = (err: any, file: any, fileList: any) => {
  console.error("上传失败:", err, file, fileList);
};

const dialogImageUrl = ref("");
const dialogVisibleImageUrl = ref(false);

const close = () => {
  spursFormRef.value.ruleFormRef.clearValidate();
  fileList.value = [];
  dialogVisible.value = false;
};
const saveSubmit = () => {
  submitForm(spursFormRef.value.ruleFormRef);
};

// 显式定义组件名称
defineOptions({
  name: "ProductAddEdit",
});
</script>

<style scoped></style>
